package com.qyhl.shop.shop.coupon;

import android.annotation.SuppressLint;
import android.text.style.TextAppearanceSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.gyf.immersionbar.ImmersionBar;
import com.qyhl.shop.R;
import com.qyhl.shop.R2;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseIViewPresenter;
import com.qyhl.webtv.basiclib.utils.Md5Builder;
import com.qyhl.webtv.basiclib.utils.NetUtil;
import com.qyhl.webtv.basiclib.utils.SpanUtils;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.shop.ShopCouponBean;
import com.qyhl.webtv.commonlib.utils.action.ActionConstant;
import com.qyhl.webtv.commonlib.utils.action.ActionLogUtils;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.qyhl.webtv.module_user.util.LoginUtils;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.weavey.loading.lib.LoadingLayout;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;
import com.zhy.adapter.recyclerview.wrapper.HeaderAndFooterWrapper;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

@Route(path = ARouterPathConstant.SHOP_COUPON_LIST)
public class ShopCouponListActivity extends BaseActivity implements ShopCouponListContract.ShopCouponListView {
    @BindView(R2.id.title)
    TextView title;
    @BindView(R2.id.recycler_view)
    RecyclerView recyclerView;
    @BindView(R2.id.refresh)
    SmartRefreshLayout refresh;
    @BindView(R2.id.load_mask)
    LoadingLayout loadMask;

    @Autowired(name = "title")
    String titleName;

    private ShopCouponListPresenter mPresenter;

    private CommonAdapter<ShopCouponBean> commonAdapter;

    private List<ShopCouponBean> mDataList = new ArrayList<>();

    private int page = 1;

    @Override
    protected int getContentView() {
        return R.layout.shop_activity_coupon_list;
    }

    @Override
    protected void setImmersionBar(ImmersionBar mImmersionBar) {
        setDefaultImmerBar();
    }

    @Override
    protected BaseIViewPresenter initBaseIViewPresenter() {
        return null;
    }

    @SuppressLint("InflateParams")
    @Override
    protected void init() {
        loadMask.setStatus(LoadingLayout.Loading);

        title.setText(titleName);

        mPresenter = new ShopCouponListPresenter(this);

        refresh.setRefreshHeader(new MaterialHeader(this));
        refresh.setRefreshFooter(new ClassicsFooter(this));
        refresh.setEnableLoadMore(true);

        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        commonAdapter = new CommonAdapter<ShopCouponBean>(this, R.layout.shop_item_coupon_list, mDataList) {
            @Override
            protected void convert(ViewHolder holder, ShopCouponBean bean, int position) {
                holder.setText(R.id.title, bean.getShopName());

                holder.setText(R.id.date, "有效期：" + bean.getBeginTime() + " ~ " + bean.getEndTime());

                RelativeLayout left = holder.getView(R.id.left_bg);
                RelativeLayout right = holder.getView(R.id.right_bg);
                TextView getBtn = holder.getView(R.id.get_btn);
                TextView couponValue = holder.getView(R.id.coupon_value);

                if (bean.isReceived()) {
                    left.setBackgroundResource(R.drawable.shop_coupon_received_left_bg);
                    right.setBackgroundResource(R.drawable.shop_coupon_received_right_bg);

                    getBtn.setTextColor(getResources().getColor(R.color.shop_common_message));
                    getBtn.setText("去使用");
                } else {
                    getBtn.setText("点击领取");
                    getBtn.setTextColor(getResources().getColor(R.color.shop_common_light));

                    SpanUtils spanUtils = new SpanUtils(ShopCouponListActivity.this);
                    if (bean.getType() == 1) {//折扣
                        left.setBackgroundResource(R.drawable.shop_coupon_discount_left_bg);
                        right.setBackgroundResource(R.drawable.shop_coupon_discount_right_bg);

                        spanUtils.append((bean.getDiscount() == 0 ? 10 : bean.getDiscount()) + "").setSpans(new TextAppearanceSpan(ShopCouponListActivity.this, R.style.shop_coupon_value))
                                .append("折").setSpans(new TextAppearanceSpan(ShopCouponListActivity.this, R.style.shop_coupon_tip));
                    } else {
                        left.setBackgroundResource(R.drawable.shop_coupon_minus_left_bg);
                        right.setBackgroundResource(R.drawable.shop_coupon_minus_right_bg);

                        spanUtils.append("¥").setSpans(new TextAppearanceSpan(ShopCouponListActivity.this, R.style.shop_coupon_tip))
                                .append(bean.getReduction() + "").setSpans(new TextAppearanceSpan(ShopCouponListActivity.this, R.style.shop_coupon_value));

                    }

                    couponValue.setText(spanUtils.create());
                }


                if (bean.getThreshold() == 0) {
                    holder.setText(R.id.coupon_limit, "无门槛");
                } else {
                    holder.setText(R.id.coupon_limit, "满" + bean.getThreshold() + "可用");
                }


                holder.setOnClickListener(R.id.get_btn, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        LoginUtils.checkLogin(new LoginUtils.LoginCallBack() {
                            @Override
                            public void login(boolean isLogin) {
                                if (isLogin) {
                                    if (bean.isReceived()) {
                                        ARouter.getInstance()
                                                .build(ARouterPathConstant.SHOP_CENTER_COUPON_DETAIL)
                                                .withInt("couponId", bean.getUserCouponId())
                                                .navigation();
                                    } else {
                                        String userName = CommonUtils.getInstance().getUserName();
                                        String sign = Md5Builder.encode(bean.getId() + "-" + userName + "-" + CommonUtils.getInstance().getSite());
                                        showLoading();
                                        mPresenter.getCoupon(userName, bean.getId(), sign);
                                    }
                                } else {
                                    RouterManager.routerLogin(ShopCouponListActivity.this, 0);
                                    showToast("尚未登录或登录已失效！");
                                }
                            }

                            @Override
                            public void error(String s) {

                            }
                        });
                    }
                });

            }
        };

        recyclerView.setAdapter(commonAdapter);

        mPresenter.getList(page);
    }

    @Override
    protected void setListener() {
        loadMask.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                loadMask.setReloadButtonText("加载中...");
                page = 1;
                mPresenter.getList(page);
            }
        });

        refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                page = 1;
                mPresenter.getList(page);
            }
        });

        refresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                mPresenter.getList(page);
            }
        });

        commonAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder viewHolder, int i) {
                ARouter.getInstance()
                        .build(ARouterPathConstant.SHOP_SHOP_DETAIL)
                        .withInt("shopId", mDataList.get(i).getShopId())
                        .navigation();

                ActionLogUtils.getInstance().onEvent(ActionConstant.SHOP_FROM_COUPON, mDataList.get(i).getShopId());
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder viewHolder, int i) {
                return false;
            }
        });
    }

    @Override
    public void setList(List<ShopCouponBean> beanList) {
        loadMask.setStatus(LoadingLayout.Success);
        loadMask.setReloadButtonText("点击重试~");
        if (beanList == null) {
            setError("暂无更多内容!");
            return;
        }
        if (page != 1) {
            refresh.finishLoadMore();
        } else {
            refresh.finishRefresh();
            mDataList.clear();
        }
        page++;
        mDataList.addAll(beanList);
        commonAdapter.notifyDataSetChanged();
    }

    @Override
    public void setError(String msg) {
        if (page != 1) {
            refresh.finishLoadMore();
            if (!NetUtil.isNetworkAvalible(this)) {
                showToast("网络异常，请检查您的网络！");
            } else if (msg.contains("暂无")) {

            } else {
                showToast(msg);
            }
        } else {
            refresh.finishRefresh();
            loadMask.setStatus(LoadingLayout.Error);
            loadMask.setReloadButtonText("点击重试~");
            if (!NetUtil.isNetworkAvalible(this)) {
                loadMask.setErrorImage(R.drawable.error_network);
                loadMask.setErrorText("网络异常，请检查您的网络！");
            } else if (msg.contains("暂无")) {
                loadMask.setErrorImage(R.drawable.empty_content);
                loadMask.setErrorText(msg);
            } else {
                loadMask.setErrorImage(R.drawable.error_content);
                loadMask.setErrorText(msg);
            }
        }
    }

    @Override
    public void getCouponResult(String msg) {
        dismissLoading();
        showToast(msg);
        page = 1;
        mPresenter.getList(page);
    }


    @OnClick(R2.id.back_btn)
    public void onClick() {
        finish();
    }

}
